import loadable from '@loadable/component';
import {loadQuery, } from "react-relay/hooks";

import  DeviceMainQuery  from "./__generated__/DeviceMainQuery.graphql";
import {useContext} from "react";
import UserContext from "../routing/UserContext";
//import queryString from "querystring";
//import {PreloadableConcreteRequest} from "react-relay/relay-hooks/EntryPointTypes";
import  DetailedGuideQuery  from "./__generated__/DetailedGuideQuery.graphql";
import {Environment} from "relay-runtime";
import {fromObjToInput, useObjToInputs, useUnitObjToInputs} from "../common/tool";


import queryString from "query-string";

/** 无法使用Hook;
 * 多层次的路由器。
 * require（）目录文件无效的不报错，但是路由secondRouter会运行出错加载父文件export失败
 * third layer
 * 如果localStrorage()来存储查询的过滤参数，路由器这里回头读取数据接口的过滤参数：有问题！不可能把URL分享给别人还能看见同一个内容的。
 没法用 const {user, setUser} =useContext(UserContext);
 若不想动态加载数据的话： & 无法利用context!只能上URL参数:来传递过滤器参数给Link/跳转的。
 React Hook "useContext" is called in function "secondRouter" that is neither a React function component nor a custom React Hook function.
 * */
export default function secondRouter(environment: Environment) {
      //const qs= queryString.parse(window.location.search); 这个位置提取URL是旧的qs并非最新的
  return (
      {
        path: '/device',
        //exact: true,  //多层路由嵌套只能去掉 true
        component: loadable(() => import('./DeviceMain')),
        prepare: (params:any) => {
            //【注意】这个里面设置断点调试，导致运行流变更，应该异步的?。
            const qs= queryString.parse(window.location.search);
            //const field =qs && !!qs.土建施单;
            //底下这个请求完全可以合并成一个请求包的：从graphql定义入手归并。||{dep:"88909",first:123}
            //const {dep ,first}=window.history.state?.myQuery; sessionStorage['设备过滤']&&

            const filt= JSON.parse(sessionStorage['设备过滤']??'{}');
            //let myobj=sessionStorage['myQuery']&&JSON.parse(sessionStorage['myQuery']);
            //有些是ID携带Name的选择项，需要剔除xxxName部分。后端只需要ID，前端揭示需要名字。组件传递参数2个都要的。
            const idfilt= fromObjToInput(filt,'useu','ispu','ispud');
            let vars={
                where: {useu: qs?.useu , ...idfilt}, after:null, first:2,
                twhere: {},
            };
            console.log("路由loadQuery前面filter=", {useu: qs?.useu , ...idfilt});
            console.log(`路由DeviceMain 使用单位@:`, params, window.history.state);
          //提前加载数据汇聚graphQL模式：只能在这里就要预备好各个接口函数所有的参数和数值。 todo: 暂时改成这样的  {fetchPolicy: 'store-or-network'} 'network-only'
            //底下filter是给主要哪一个查询配合简易搜索框立刻查询用的，两种模式的查询参数注入。尽量DeviceMainQuery保持单一个查询最好，避免参数名字混淆冲突。
            return {
            myQuery: loadQuery(
                environment as any,
                DeviceMainQuery as any,
                vars,
                { fetchPolicy: 'network-only' },
            ),
            filter : {where:{useu: qs?.useu , ...idfilt},
                offset:0, first:3 }
          };
        },
        routes:[
            {
                path: '/device/new',
                exact: true,
                component: loadable( () => import('./NewDevice')),
            },
            {
                path: '/device/:id',
                exact: true,
                component: loadable(() => import('./DetailedGuide')),
                prepare: (params:any) => {
                    console.log(`路由历史state7-点击路由params:`, params, window.history.state);
                    return {
                        eqpQuery: loadQuery(
                            environment as any,
                            DetailedGuideQuery as any,
                            {
                                id: params.id,
                            },
                            { fetchPolicy: 'store-or-network' },
                        ),
                    };
                },
            },
        ],
      }
  );
}

//export default SecondRouter();

